package com.joe.demo.nio.io;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description
 * @Author gaojw
 * @Date 2024-08-28
 */
@Slf4j
public class MultiThreadServer {

    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("BOSS");
        final ServerSocketChannel server = ServerSocketChannel.open();
        server.configureBlocking(false);
        final Selector selector = Selector.open();
        server.register(selector, SelectionKey.OP_ACCEPT);
        server.bind(new InetSocketAddress(8080));

        // 1.创建固定数量的worker
        Worker[] workers = new Worker[2];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("worker-" + i);
        }
        final AtomicInteger index = new AtomicInteger();

        while (true){
            selector.select();
            final Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                final SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()){
                    final SocketChannel socketChannel = server.accept();
                    socketChannel.configureBlocking(false);
                    log.info("connected..., {}", socketChannel);
                    log.info("register before..., {}", socketChannel.getRemoteAddress());
                    // 轮询
                    workers[index.getAndIncrement() % workers.length].register(socketChannel);
                    log.info("register after..., {}", socketChannel.getRemoteAddress());
                }
            }
        }
    }

    static class Worker implements Runnable {
        private Thread thread;
        private Selector selector;
        private String name;
        // 标记是否初始化
        private volatile boolean start = false;
        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();

        public Worker(String name) {
            this.name = name;

        }

        // 初始化线程和 selector
        public void register(SocketChannel socketChannel) throws IOException {
            if (!start){
                selector = Selector.open();
                thread = new Thread(this, name);
                thread.start();
                start = true;
            }
            // 向队列添加了任务
            queue.add(()->{
                try {
                    socketChannel.register(selector, SelectionKey.OP_READ, null);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
            selector.wakeup();

            // selector.wakeup();
            // socketChannel.register(selector, SelectionKey.OP_READ, null);
        }

        @Override
        public void run() {
            while (true){
                try {
                    selector.select();
                    final Runnable task = queue.poll();
                    if (task != null){
                        task.run();
                    }
                    final Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        final SelectionKey key = iterator.next();
                        iterator.remove();
                        if (key.isReadable()){
                            final SocketChannel socketChannel = (SocketChannel) key.channel();
                            socketChannel.configureBlocking(false);

                            final ByteBuffer buffer = ByteBuffer.allocate(10);
                            socketChannel.read(buffer);
                            buffer.flip();
                            log.info("selector 接收到的数据：{}", StandardCharsets.UTF_8.decode(buffer));
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
